# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import fields, models, api

import logging
_logger = logging.getLogger(__name__)

import random


class IotSensorType(models.Model):
    _name = "iot.sensor.type"
    _description = 'IotSensorType'
    _order = "name"

    name = fields.Char(index=True)
    code = fields.Char(index=True)

    # a field for uom should be defined
    # uom

    _sql_constraints = [
        ('unique_code', 'UNIQUE (code)',  'code is unique!')
    ]

    @api.model
    def search_by_code(self, code):
        return self.search([('code', '=', code)])


class IotSensor(models.Model):
    _name = "iot.sensor"
    _description = 'IotSensor'
    _order = "name"

    name = fields.Char(index=True)
    code = fields.Char(index=True)
    
    user_id = fields.Many2one('res.users', 'User', related='device_id.user_id')
    partner_id = fields.Many2one('res.partner', 'Partner', related='device_id.partner_id' )
    company_id = fields.Many2one('res.company', related='device_id.company_id')
    project_id = fields.Many2one('iot.project', related='device_id.project_id')
    gateway_id = fields.Many2one('iot.gateway', related='device_id.gateway_id')
    device_id = fields.Many2one('iot.device', 'Device', ondelete='cascade', index=True)

    sensor_type_id = fields.Many2one('iot.sensor.type', 'Sensor Type', ondelete='restrict', index=True)

    latitude = fields.Float(string='Latitude', digits=(16, 5), related='device_id.latitude')
    longitude = fields.Float(string='Longitude', digits=(16, 5), related='device_id.longitude')

    depth = fields.Integer(string='Depth', default=0, help="UOM mm" )

    
    value_ids = fields.One2many('iot.value', 'sensor_id', string='Values')
    value = fields.Integer(string='Value', compute="_compute_value", help="UOM mm" )
    time = fields.Datetime(string="check Time", compute="_compute_value" )

    _sql_constraints = [
        ('unique_code', 'UNIQUE (code)',  'code is unique!')
    ]

    def _compute_value(self):
        for rec in self:
            value_id = self.value_ids.search([['id','in', rec.value_ids.ids]], limit=1, order="id desc")
            rec.value = value_id and value_id.value or 0 
            rec.time = value_id.time


    @api.model
    def search_by_code(self, code):
        return self.search([('code', '=', code)])

    @api.model
    def update_sensors(self, device, sensors):
        for sensor in sensors:
            obj = self.search_by_code(sensor.get('code'))

            values = {
                'device_id': device.id,
                'code': sensor.get('code'), 
                'name': sensor.get('name'), 
                'depth': sensor.get('depth'), 
                'sensor_type_id': self.env['iot.sensor.type'
                    ].search_by_code( sensor.get('sensor_type') ).id

            }

            if not obj:
                obj = obj.create(values)
            else:
                obj.write(values)


class IotValue(models.Model):
    _name = "iot.value"
    _description = 'IotValue'
    _order = "id desc"

    code = fields.Char(index=True)
    name = fields.Char(related='code')

    time = fields.Datetime(string="check Time")

    user_id = fields.Many2one('res.users', 'User', related='project_id.user_id')
    partner_id = fields.Many2one('res.partner', 'Partner', related='project_id.partner_id' )
    company_id = fields.Many2one('res.company', related='project_id.company_id')
    project_id = fields.Many2one('iot.project', ondelete='cascade' )
    
    gateway_id = fields.Many2one('iot.gateway',)
    device_id = fields.Many2one('iot.device', 'Device', index=True)
    sensor_id = fields.Many2one('iot.sensor', 'Device', index=True)

    sensor_type_id = fields.Many2one('iot.sensor.type', 'Sensor Type', index=True)

    latitude = fields.Float(string='Latitude', digits=(16, 5) )
    longitude = fields.Float(string='Longitude', digits=(16, 5) )
    depth = fields.Integer(string='Depth', default=0, help="UOM mm" )
    value = fields.Integer(string='Value', default=0, help="UOM mm" )

    @api.model
    def action_sensor(self):
        sensors = self.env['iot.sensor'].search([])
        for sensor in sensors:
            values = {
                'code': sensor.code, 
                'sensor_id': sensor.id,
                'device_id': sensor.device_id.id,
                'gateway_id': sensor.gateway_id.id,
                'project_id': sensor.project_id.id,
                'latitude': sensor.latitude, 
                'longitude': sensor.longitude, 
                'sensor_type_id': sensor.sensor_type_id.id,
                'depth': sensor.depth, 
                'time': fields.Datetime.now(), 
                'value': random.randint(10, 100), 
            }

            self.create(values)

    @api.model
    def update_values(self, sensors):
        for sensor in sensors:
            sensor_id = self.sensor_id.search_by_code(sensor.get('code'))

            if not sensor_id:
                # server and gateway is not same config. 
                continue

            values = {
                'code': sensor.get('code'), 
                'sensor_id': sensor_id.id,
                'device_id': sensor_id.device_id.id,
                'gateway_id': sensor_id.gateway_id.id,
                'project_id': sensor_id.project_id.id,
                'latitude': sensor_id.latitude, 
                'longitude': sensor_id.longitude, 
                'sensor_type_id': sensor_id.sensor_type_id.id,
                'depth': sensor_id.depth, 
                'time': sensor.get('time'), 
                'value': sensor.get('value'), 
            }

            self.create(values)

